package com.wangsh.train.common.util;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;

import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wangsh.train.common.pojo.ApiResponse;
import com.wangsh.train.common.pojo.ApiResponseEnum;

/**
 * ip的工具类
 * @author TeaBig
 *
 */
@Component
public class IpUtil
{
	@Resource
	private HttpUtil httpUtil ; 
	
	/* 核心工具类 */
	private static DbSearcher dbSearcher ;
	
	/* 初始化数据 */
	static
	{
		String dbFile = ConstatFinalUtil.CONFIG_JSON.getString("outer.config.path") + ("ip2region.db") + "";
		ConstatFinalUtil.SYS_LOGGER.info("==dbFile:{}==",dbFile);
//		try
//		{
//			//String dbFile = "d:/test/data/ip2region.db" ; 
//			/* 初始化 */
//			DbConfig dbConfig = new DbConfig();
//			dbSearcher = new DbSearcher(dbConfig, dbFile);
//		} catch (Exception e)
//		{
//			ConstatFinalUtil.SYS_LOGGER.info("初始化ip报错了",e);
//		}
	}
	
	/**
	 * ip定位
	 * @return
	 */
	public JSONObject ipLocation(String ip)
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		try
		{
			DataBlock dataBlock = dbSearcher.memorySearch(ip);
			
			/* 只存储地区信息 */
			Map<String, Object> dataMap = new HashMap<String, Object>();
			/* 地区信息 */
			dataMap.put("region", dataBlock.getRegion());
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
			
			/* 设置响应码 */
			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} catch (IOException e)
		{
			ConstatFinalUtil.SYS_LOGGER.info("ip定位报错了;ip:{}",ip,e);
			
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse.toJSON() ; 
	}
	
	/**
	 * 请求埃文更详细的信息
	 * 网址:
		https://mall.ipplus360.com/center/ip/api?ip=1.198.22.76&type=locate&coordsys=BD09
		https://mall.ipplus360.com/center/ip/api?ip=1.198.22.76&type=district&coordsys=BD09
		type:
		locatepsi:公安
		locate:商业数据
		district:县级数据
		city:城市数据
		验证当前查询剩余的次数:
		https://mall.ipplus360.com/center/isExistCount?productType=locate&ip=1.193.82.212
		
		查询剩余次数
		https://mall.ipplus360.com/center/isExistCount?productType=district&ip=1.198.22.169
	 */
	public JSONObject ipDetail(String ip)
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		
		/* 请求服务器 */
		String response;
		try
		{
			String urlStr = "https://mall.ipplus360.com/center/ip/api" ;
			Map<String, String> headerMap = new HashMap<String, String>();
			Map<String, String> paramsMap = new HashMap<String, String>();
			paramsMap.put("ip", ip);
			paramsMap.put("type", "district");
			paramsMap.put("coordsys", "BD09");
			Map<String, String> responseMap = new HashMap<String, String>();
			/* 随机的请求头 */
			ConstatFinalUtil.headerRandom(headerMap);
			/* get请求 */
			response = httpUtil.methodGet(urlStr, headerMap, paramsMap, responseMap);
			JSONObject responseJSON = JSON.parseObject(response);
			if(responseJSON != null && "success".equalsIgnoreCase(responseJSON.getString("code")))
			{
				JSONObject responseDataJSON = (JSONObject) responseJSON.get("data");
				
				/* 目标位置 */
				double radiusTar = 0 ; 
				JSONObject areaTarJSON = null ; 
				/* 取出一个半径最小的 */
				JSONArray areaArr = (JSONArray) responseDataJSON.get("multiAreas");
				for (Iterator iterator = areaArr.iterator(); iterator.hasNext();)
				{
					JSONObject areaTemp = (JSONObject) iterator.next();
					double radiusTemp = areaTemp.getDoubleValue("radius");
					if(radiusTar > 0)
					{
						/* 原来有半径 */
						if(radiusTar > radiusTemp)
						{
							radiusTar = radiusTemp ; 
							areaTarJSON = (JSONObject) areaTemp.clone() ;
						}
					}else
					{
						radiusTar = radiusTemp ; 
						areaTarJSON = (JSONObject) areaTemp.clone() ;
					}
				}
				
				responseDataJSON.put("minArea", areaTarJSON);
				
				apiResponse.setDataOne(responseDataJSON);
			}
			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
			/* 设置响应码 */
			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
			ConstatFinalUtil.SYS_LOGGER.info("--返回结果:{}--",response);
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.info("ip请求埃文报错了;ip:{}",ip,e);
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse.toJSON() ; 
	}
}
